using MediatR;
using ProduceBasicData.Api.Application.Command.Material.GroupType;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.GroupType
{
    /// <summary>
    /// 群组类型查询处理类
    /// </summary>
    public class GetGroupTypeHandler : IRequestHandler<GetGroupTypeCommand, ApiResult<List<GroupTypeDTO>>>
    {
        private readonly IBaseRespository<GroupTypeDictionary> groupTypeRepository;

        public GetGroupTypeHandler(IBaseRespository<GroupTypeDictionary> groupTypeRepository)
        {
            this.groupTypeRepository = groupTypeRepository;
        }

        public Task<ApiResult<List<GroupTypeDTO>>> Handle(GetGroupTypeCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<GroupTypeDTO>>();

            try
            {
                // 获取群组类型数据
                var query = groupTypeRepository.GetAll().Where(x => !x.Isdel);

                // 如果只获取启用的类型
                if (request.OnlyEnabled)
                {
                    query = query.Where(x => x.IsEnabled);
                }

                // 映射到DTO
                var groupTypes = query
                    .OrderBy(x => x.SortOrder)
                    .Select(x => new GroupTypeDTO
                    {
                        Id = x.Id,
                        GroupTypeCode = x.GroupTypeCode,
                        GroupTypeName = x.GroupTypeName,
                        GroupTypeDesc = x.GroupTypeDesc,
                        RequireDefaultCraft = x.RequireDefaultCraft,
                        SortOrder = x.SortOrder,
                        IsEnabled = x.IsEnabled
                    })
                    .ToList();

                result.Data = groupTypes;
                result.Code = ApiEnum.Success;
                result.Msg = "群组类型查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"群组类型查询异常：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
}
